404 error with POST and OkHttp3 - android

I'm having an issue posting data to the Challonge API with OkHttp3 on Android... This is the jist of my code:
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = new HttpUrl.Builder();
urlBuilder = HttpUrl.parse("https://api.challonge.com/v1/tournaments/"+EVENT_ID+".json")
.newBuilder();
RequestBody postBody = new FormBody.Builder()
.add("_method", "post")
.add("api_key", API_KEY)
.add("participant[name]", name.getText().toString())
.add("participant[misc]", forum_id.getText().toString())
.build();
Request request = new Request.Builder()
.url(urlBuilder.build().toString())
.post(postBody)
.build();
Response response = client.newCall(request).execute();
No matter what I do, the resulting reponse is a 404 page.
If I do a GET response to the same URL, I get a proper response. However, the moment I add .post(postBody) to the request, its immediately 404s.
The documentation for the Challonge API is here:
http://api.challonge.com/v1/documents/participants/create

It looks to me like you're just using the wrong URL. The URL you've got there, "https://api.challonge.com/v1/tournaments/"+EVENT_ID+".json", is the URL for retrieving a single tournament, as seen here. This link was meant to receive GET requests.
According to the link you provided, you should alter your code to POST to https://api.challonge.com/v1/tournaments/"+EVENT_ID+"/participants.json

Related

OkHttp - Adding attributes to body

Does anyone have experience with the OkHttp websocket library? I'm creating a simple chatroom app and my current issue is when my android client connects to the websocket server, it only gives the client's connection id. I'm trying add attributes to the body of the request, but I can't seem to get it working with OkHttp.
RequestBody requestBody = new FormBody.Builder()
.add("room_id", "e9502c54-927c-4639-a94f-8d03149c9c62")
.build();```
Request request = new Request.Builder()
.url("wss://mywebsocketurl.com")
.method("POST", requestBody)
.build();
Request request = new Request.Builder()
.url("wss://mywebsocketurl.com")
.post(requestBody)
.build();
I'm trying to add a room_id so when the user is successfully connected, it logs the connectionid+roomid to manage the chat rooms however I can't figure out how to add attributes to the body
Edit 1:
Request request = new Request.Builder()
.url("wss://mywebsocketurl.come")
.build();
EchoWebSocketListener listener = new EchoWebSocketListener();
ws = client.newWebSocket(request, listener);
This works when establishing the connection for the first time, but I can't seem to figure out how to add body attributes to this.

OkHTTP how to replace team_number from url POST

I have url like this.
http://host/parallel/team/:team_number.json
and it has post params.
like team_number, team_name.
How to make a post request such that i replace team_number to team number with a value.
Does :team_number need to be handled differently ?
So far i have done
RequestBody formBody = new FormBody.Builder()
.addEncoded(TEAM_NUMBER,tracking_number)
.add(TRACK_NAME, name)
.build();
Request request = new Request.Builder()
.url(SEND_TRACKING_DATA)
.post(formBody)
.build();
Response response = CoreApplication.okHttpClient.newCall(request).execute();
return response.body().string();

Correct syntax for adding parameters to get() and post() request using okhttp in Android

What I want to achieve ?
I am trying to send two parameters in my Server URL using OkHttp through both get and post bcoz i want to know the syntax for both the methods.
What I had Tried ?
I have searched SO for questions on OkHttp but those had not solved my IllegalArgumentException.
I have seen below links :
Add query params to a GET request in okhttp in Android
and this
How to add parameters to api (http post) using okhttp library in Android
and
How to add query parameters to a HTTP GET request by OkHttp?
Exception from code 2:
Code I had used till now :
1)GET
urls = chain.request().httpUrl() <-- NullPointerException Line
.newBuilder()
.scheme("http")
.host(SERVER_IP)
.addQueryParameter("from", valueFrom)
.addQueryParameter("to",valueTo)
.build();
request = chain.request().newBuilder().url(urls).build();
response = chain.proceed(request);
2)GET
urls =new HttpUrl.Builder()
.host(SERVER_IP) <--- IllegalArgumentException line
.addQueryParameter("from", valueFrom)
.addQueryParameter("to", valueTo)
.build();
request = new Request.Builder().url(urls).build();
response = client.newCall(request).execute();
3)POST
body = new
MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("from",
valueFrom).addFormDataPart("to",valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
4)POST
body = new FormEncodingBuilder().add("from", valueFrom).add("to",
valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
build.gradle
dependencies
{
compile files('libs/okhttp-2.5.0.jar')
compile files('libs/okio-1.6.0.jar')
}
Thanks In Advance...
Edit :
The above code for POST request is working fine now
But for GET request I still have no solution.
Just set your GET parameter extend your URL:
RequestBody body = new FormEncodingBuilder()
.add("requestParamName", requestParameter.getRequestParams())
.build();
Request request = new Request.Builder()
.url("https://www.test.com/serviceTest?parama=abc&paramb=123")
.post(body)
.build();

Appending a param value to a url while making network request in android using okhttp

What I was doing:
I was using android http library to make http requests
What i am doing:
I have migrated into Oktttp now and i am using below code
In doInBackground of an AsyncTask i am calling the below function
public static String getRequestNoPayload(String urlString) throws Exception {
client.setConnectTimeout(20, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(20, TimeUnit.SECONDS); // socket timeout
Request request = new Request.Builder()
.url(urlString)
.addHeader("phonenumber",AppController.getPhoneNumber())
.addHeader("authtoken",AppController.getAuthCode())
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
value of url:
String urlString=Keys.login_api+"?phonenumber="+edtPhnoId.getText().toString().trim();
What is happening:
Not able to send requests like this since i am appending the url with
a param ?
How to resolve this ... should i go for any specific encoding
methods, if so which is that one
Any sample would help
Try this
RequestBody formBody = new FormEncodingBuilder()
.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();
https://publicobject.com/2014/06/12/okhttp-ate-mimecraft/

OkHttp gzip post body

I am trying to migrate my Android project to OkHttp.
What I am wondering is if OkHttp will compress the body of my POST requests with gzip?
I am using it like this (from the example on the home page):
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Will this RequestBody actually gzip the json if it's "big enough", or do I need to do this manually? Like I did before with AndroidHttpClient like this:
AndroidHttpClient.getCompressedEntity(json, context.getContentResolver())
If I need to do it manually, what is the best approach?
Thank you!
According to GitHub issues for OkHttp, we should do it manually:
https://github.com/square/okhttp/issues/350
"For the time being your best option is to do it manually: compress the content and add Content-Encoding: gzip."
This is how I'm doing it now:
byte[] data = json.getBytes("UTF-8");
ByteArrayOutputStream arr = new ByteArrayOutputStream();
OutputStream zipper = new GZIPOutputStream(arr);
zipper.write(data);
zipper.close();
RequestBody body = RequestBody.create(JSON, arr.toByteArray());
Request request = new Request.Builder()
.url(url)
.post(body)
.header("Content-Encoding", "gzip")
.build();
I took the code from the AndroidHttpClient from here, and just using it inline without the ByteArrayEntity:
http://grepcode.com/file/repo1.maven.org/maven2/org.robolectric/android-all/4.2.2_r1.2-robolectric-0/android/net/http/AndroidHttpClient.java#AndroidHttpClient.getCompressedEntity%28byte%5B%5D%2Candroid.content.ContentResolver%29
Knowing it's too late to answer but if anyone might need it in future.
A newer and easier way to do this is by following
val request = Request.Builder().url("…")\ .addHeader("Content-Encoding", "gzip")\ .post(uncompressedBody.gzip())\ .build()
More details can be found here

Categories

Resources