I'm trying to send post/put request to my service using OkHttp library.
private static final String SERVICE = "service_url";
private static final MediaType JSON = MediaType.parse("text/json");
private OkHttpClient mClient = new OkHttpClient();
//---------------------------------------------------------------
Request req = new Request.Builder()
.url(SERVICE)
.put(RequestBody.create(JSON, body))
.build();
try {
Response httpResp = mClient.newCall(req).execute();
resp = httpResp.body().string();
} catch (IOException ex) {
ex.printStackTrace();
}
But this code sends GET request, not PUT. The same situation will be if I use .post.
I was trying to use HttpURLConnection and I've got the same result.
What am I doing wrong?
Related
This question already has answers here:
Sending JSON body through POST request in OKhttp in Android
(2 answers)
Closed 4 years ago.
for normal json like
{
"text1":"going",
"text2":"sending"
}
i'm using okhttp3 as
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("text1",xxx)
.addFormDataPart("text2","yyy")
.build();
how do i use it to send for jsons like
{"Text1":"aaa","text2":[{"module":"bbb","Text":"xxx","params":{"lang": "eng"}}]}
Try this
Add Gradle depends compile 'com.squareup.okhttp3:okhttp:3.2.0'
public static JSONObject foo(String url, JSONObject json) {
JSONObject jsonObjectResp = null;
try {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
okhttp3.RequestBody body = RequestBody.create(JSON, json.toString());
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(body)
.build();
okhttp3.Response response = client.newCall(request).execute();
String networkResp = response.body().string();
if (!networkResp.isEmpty()) {
jsonObjectResp = parseJSONStringToJSONObject(networkResp);
}
} catch (Exception ex) {
String err = String.format("{\"result\":\"false\",\"error\":\"%s\"}", ex.getMessage());
jsonObjectResp = parseJSONStringToJSONObject(err);
}
return jsonObjectResp;
}
I'm trying to download image from server with POST (json body). To accomplish that I created okhttp interceptor:
private static class PostThumbnailRequestInterceptor implements Interceptor {
private static final String DEVICE_GUID = "device_guid";
private static final String RESOURCE_GUIDS = "resource_guids";
private static final String UTC_TIMESTAMP = "utc_timestamp";
private String mChannelGuid;
private String mResourceGuid;
public PostThumbnailRequestInterceptor(String channelGuid, String resourceGuid) {
mChannelGuid = channelGuid;
mResourceGuid = resourceGuid;
}
#Override
public Response intercept(Chain chain) throws IOException {
final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
JSONArray resources = new JSONArray();
resources.put(mResourceGuid);
JSONObject requestedThumbnail = new JSONObject();
JSONObject payload = new JSONObject();
try {
requestedThumbnail.put(UTC_TIMESTAMP, System.currentTimeMillis() * 1000);
requestedThumbnail.put(DEVICE_GUID, mChannelGuid);
requestedThumbnail.put(RESOURCE_GUIDS, resources);
payload.put("thumbnails", new JSONArray() {{put(requestedThumbnail);}});
} catch (JSONException e) {
throw new IOException("Failed to create payload");
}
RequestBody body = RequestBody.create(JSON, payload.toString());
final Request original = chain.request();
final Request.Builder requestBuilder = original.newBuilder()
.url(original.url())
.post(body);
//return chain.proceed(requestBuilder.build());
Response response = chain.proceed(requestBuilder.build());
try {
MediaType contentType = MediaType.parse("data:image/jpeg;base64");// response.body().contentType();
JSONObject object = new JSONObject(response.body().string());
String base64String = object.optJSONArray("thumbnails").getJSONObject(0).optString("content");
base64String = base64String.replace("data:image/jpeg;base64,", "");
byte[] rawImage = Base64.decode(base64String , Base64.DEFAULT);
ResponseBody realResponseBody = ResponseBody.create(contentType, rawImage);
response = response.newBuilder().body(realResponseBody).build();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
}
And using it like this
OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(new PostThumbnailRequestInterceptor(channel.id.getServerId(), channel.id.getChannelId()))
.build();
GlideApp.get(getContext())
.getRegistry().replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(mOkHttpClient));
It is works well with 1 request per time, but if I bind it with recycler view, replacing classes in Glide with dynamic interceptor produce a lot of errors (failed to load resource).
Am I on right way to request post or it is only 1 way - firstly request as usual and then pass decoded bytes to Glide?
I am trying to connect with my webservice restful to login a user.
i do that:
private class LoginTask extends AsyncTask {
OkHttpClient client = new OkHttpClient();
String base64NamePass;
public LoginTask(String base64NamePass){
this.base64NamePass = base64NamePass;
}
#Override
protected Object doInBackground(Object[] params) {
Response response = null;
try {
response = get("http://192.168.0.27:8080/ServicioRestTFG/rest/UsuariosServicesRs/login", base64NamePass);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
private Response get (String url, String base64NamePass) throws IOException {
Request request = new Request.Builder()
.get()
.url(url)
.addHeader("Authorization", base64NamePass)
.build();
return client.newCall(request).execute();
}
}
First i encoded the user and the pass with base64 and then i send it to my server.
But when i add the header:
Request request = new Request.Builder()
.get()
.url(url)
.addHeader("Authorization", base64NamePass)
.build();
return client.newCall(request).execute();
the app forceclosed and it doesnt show me what is the error, only close.
Any idea?
thanks
I have used this method https://stackoverflow.com/a/31744565/5829906 but doesnt post data.
Here is my code
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("rating", "5").addFormDataPart("comment", "Awesome")
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
response.body().close();
}catch (Exception e) {
e.printStackTrace();
}
I tried DefaultHttpClient , that seems to be working, but it shows deprecated, so thought of trying something different..Cant figure out what is wrong in this
You select MediaType MultipartBuilder.FORM
which is for uploading the file/image as multipart
public static final MediaType FORM = MediaType.parse("multipart/form-data");
try to send like this as
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build();
Request request = new Request.Builder().url("https://en.wikipedia.org/w/index.php").post(formBody).build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
For those that may still come here, using with Retrofi2 and passing your data correctly to the request body. Even if you set "application/x-www-form-urlencoded" and you did not pass your data properly, you will still have issue. That was my situstion
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("ContentType", "application/x-www-form-urlencoded");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api api = retrofit.create(Api.class);
Then make sure you pass your data to your api endpoint as shown below. NOT as JSON, or class object or string but as request body.
RequestBody formBody = new FormBody.Builder()
.addEncoded("grant_type", "password")
.addEncoded("username", username)
.addEncoded("password", password)
.build();
call your api service
Call<Response> call = api.login(formBody);
I hope this helps somebody
I'm pulling my hair out trying to get this to work. I'm using OkHTTP to make a POST request to my server. However, every method I've tried of making a successful POST request with parameters, causes the server to go down, giving me a response of '503 service unavailable'. I use exterior clients to test the server, like the Advanced Rest Client extension, and it works perfectly fine.
The URL for the API is in the format of "https://mystuff-herokuapp.com/postuser" and my body parameters are "user_id", "userName", "email". I've tried adding headers to the request, changing from FormBodyEncoding() to MultiPartBuilder(), etc etc.
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//set toolbar as the acting action bar
Toolbar actionToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(actionToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Intent intent = getIntent();
String photoUrl = intent.getStringExtra("photo");
String userTwitterID = intent.getStringExtra("userID");
String userName = intent.getStringExtra("name");
String userEmail = intent.getStringExtra("email");
JSONObject jObject = new JSONObject();
try {
jObject.put("user_id", userTwitterID);
jObject.put("userName", userName);
jObject.put("userEmail", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
new UserApiProcess().execute(jObject);
}
Async Task
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBuilder()
.addFormDataPart("user_id", "800")
.addFormDataPart("userName", "Nick")
.addFormDataPart("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Successful Response from Advanced Rest Client
My Server Error through Android
Try this. It should work.
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodinBuilder()
.add("user_id", "800")
.add("userName", "Nick")
.add("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}