반응형
JSON으로서의 OkHttp Post Body
그래서 Koush's Ion을 사용했을 때 간단한 방법으로 json body를 게시물에 추가할 수 있었습니다..setJsonObjectBody(json).asJsonObject()
저는 OkHttp로 옮기는데, 그렇게 하는 게 좋은 방법이 아닌 것 같아요.여기저기서 오류 400이 나오네요.
생각나는 사람?
json 문자열로 수동 포맷도 해봤습니다.
String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);
String url = mBaseUrl + "/" + id + "/report";
Request request = new Request.Builder()
.header("X-Client-Type", "Android")
.url(url)
.post(RequestBody
.create(MediaType
.parse("application/json"),
"{\"Reason\": \"" + reason + "\"}"
))
.build();
client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
@Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException(
"Unexpected code " + response);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});
}
});
/*Ion.with(getContext(), url)
.setHeader("X-Client-Type", "Android")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});*/
그냥 사용하다JSONObject.toString();
OkHttp의 튜토리얼을 보세요.
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON); // new
// RequestBody body = RequestBody.create(JSON, json); // old
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
직접 만들 수 있습니다.JSONObject
그리고나서toString()
.
백그라운드 스레드로 실행해 주세요.doInBackground
에AsyncTask
.
OkHttp 버전> 4:
import okhttp3.MediaType.Companion.toMediaType
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp 버전 3:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
또 다른 접근법은FormBody.Builder()
.
콜백의 예를 다음에 나타냅니다.
Callback loginCallback = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// String loginResponseString = response.body().string();
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i(TAG, "loginResponseString: " + loginResponseString);
}
};
그런 다음 우리 자신의 몸을 만듭니다.
RequestBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", password)
.add("customCredential", "")
.add("isPersistent", "true")
.add("setCookie", "true")
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(this)
.build();
Request request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
마지막으로 서버를 호출합니다.
client.newCall(request).enqueue(loginCallback);
kotlin, okhttp v4.* 그렇게 동작하고 있습니다.
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
언급URL : https://stackoverflow.com/questions/34179922/okhttp-post-body-as-json
반응형
'sourcecode' 카테고리의 다른 글
각도용 리치 텍스트 편집기JS (0) | 2023.04.03 |
---|---|
FeedWordpress Import에 속하는 이미지의 사이즈가 조정됩니다만, 어디에 있습니까? (0) | 2023.04.03 |
객체 속성 액세스를 위한 선택적 체인 연산자 사용 (0) | 2023.04.03 |
wp-content에 대한 파일 권한을 docker-compose용 공식 워드프레스 이미지로 수정하는 방법 (0) | 2023.04.03 |
AngularJS : 공장 대신 서비스를 사용하는 경우 (0) | 2023.04.03 |