Post a request in java [duplicate] - java

This question already has answers here:
How to add parameters to api (http post) using okhttp library in Android
(9 answers)
Closed 6 years ago.
Recently I want use a search interface.But I am confused by the request body.
According to reference,when you need to search in their site,you can do like this:
curl -d "keyword=android" http://gankio.herokuapp.com/search
So how to post a this request in java rather than curl?
I have tried useing okhttp.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
String json = "keyword=android";
RequestBody body = RequestBody.create(JSON,json);
Request request = new Request.Builder()
.url("http://gankio.herokuapp.com/search")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("TAG",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();`

I have solved this question.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder().add("keyword", "android").build();
Request request = new Request.Builder()
.url("http://gankio.herokuapp.com/search")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("TAG", response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();

You want to call the service using post request and form param, please use the below code:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://gankio.herokuapp.com/search?keyword=android")
.post( RequestBody.create(MediaType.parse("application/json; charset=utf-8"), ""))
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.toString());
System.out.println(response.body().string());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Response response = client.newCall(request).execute();
The service that you want to call does not need any body to pass, only it needs form parameter (keyword) with value (android), but you are trying to pass the parameter using the body, and this is your mistake

You can try using HttpUrlConnection from java.net
This link will explain HttpUrlConnection connection process.

Related

I got different results when call simple GET Request with curl and java okhttp

I call below URL using cURL
curl 'http://username:password#192.168.1.108/merlin/Login.cgi'
and I get proper response
{ "Session" : "0xb3e01810", "result" : { "message" : "OK", "num" : 200 } }
I get the same response from browser (directly open link), postman and even with NodeJs,
but I get response code 401 when send GET_Request to this url using okhttp in java
my java code with okhttp is
Request request = new Request.Builder()
.url("http://username:password#192.168.1.108/merlin/Login.cgi")
.build();
try {
com.squareup.okhttp.Response response = client.newCall(request).execute();
System.out.println(response.code());
} catch (IOException e) {
e.printStackTrace();
}
Use basic authentication. Having username and password in the url, separated with :, is the same as basic authentication. I tested and it's ok. my snippet is:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://192.168.1.108/merlin/Login.cgi")
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString("username:password".getBytes()))
.get().build();
try (Response response = client.newCall(request).execute()) {
assert response.body() != null;
String res = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}

Getting Request method 'GET' not supported in java using OkHTTP Client and HttpsURLConnection

As I need to send data through post for initiating the API, but getting get not supported error. Even I'm using post method ,Please suggest where I did mistake. I have tried OkHTTPClient and HTTPsURL connection, still getting same error
Error: **{"timestamp":"2021-03-23T06:26:43.508+0000","status":405,"error":"Method Not Allowed","message":"Request method 'GET' not supported","path":"/stsBankResponse/"}**
When I directly hit the URL in browser that time also getting method not allowed ,its valid error but programmatically using Post only even though same error
JSONObject jsobj=new JSONObject();
jsobj.put("authmode", "Abc");
JSONArray jaarray = new JSONArray();
jaarray.put(jsobj);
JSONObject mainObj = new JSONObject();
mainObj.put("bankResponseDtl", jaarray);
String str_jsonparams = String.valueOf(mainObj);
System.out.println("PU_Auth str_jsonparams->"+str_jsonparams);
String proxyhost=common_utility.getProxyHost();
String proxyport=common_utility.getProxyPort();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyhost, new Integer(proxyport)));
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30, TimeUnit.SECONDS);
builder.readTimeout(30, TimeUnit.SECONDS);
builder.writeTimeout(30, TimeUnit.SECONDS);
builder.proxy(proxy);
client = builder.build();
RequestBody body = RequestBody.create(JSON, str_jsonparams);
Request request = new Request.Builder()
.url(common_utility.getEmandateServerResponeURL())
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
System.out.println("ECEEEEE"+e);
}
#Override
public void onResponse(Call arg0, Response arg1) throws IOException {
}
});

Java HttpServlet unable to receive any parameters from POST request made by client using OKHttp

This is the log from the server:
POST Request reader reads:--3cd58f21-8ffa-46a0-b1c0-0e4660c2ca28
POST Request reader reads:Content-Disposition: form-data; name="device"
POST Request reader reads:Content-Length: 163
POST Request reader reads:
POST Request reader reads:{"deviceId":"5ccf7f0fb7b1","manufacturer":"Wow Lamp","name":"Wow-b7b1","type":"lamp","userId":"amzn1.account.AGGL3JOPQ3UTF74KQY2TJCYSYNAQ","timer":0,"chosen":true}
POST Request reader reads:--3cd58f21-8ffa-46a0-b1c0-0e4660c2ca28--
The result above is what the reader read from the request. But if getParameter is called from the request instance, the parameter map is null.
This is the content of the parameter map:
POST Request:{}
As you can see, the map contains no parameter, but the reader can read the data sent by the client.
This is the code of the server:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException
{
System.out.println("POST Request:" + req.getParameterMap());
if(isPostRequestValid(req))
{
try
{
handleRequest(req);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
sendResponse(resp);
try
{
BufferedReader reader = req.getReader();
String inputLine;
while((inputLine = reader.readLine()) != null)
{
System.out.println("POST Request reader reads:" + inputLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
There must be some coding mistake in the client side
This is the code of the client:
new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM) //this is what I say in my POSTman (Chrome plugin)
.addFormDataPart("device", device)
.build();
Request request = new Request.Builder()
.url(Constant.BASE_URL + "update_device.html")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
response.body().close();
// do whatever you need to do with responseString
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
But the client side did use form data, so what can be wrong here?
I have solve the problem by updating my OKHttpClient to version 3.6 and then change the request body part of my code to this
RequestBody formBody = new FormBody.Builder()
.add("key", "value")
.build();
It seems that my version of OKHttpClient before does not include the functionality to send parameters of content type application/x-www-form-urlencoded.
Before updating, OKHttpClient can only send parameter of content type multipart/form-data. But for the servlet side, I was unable to parse this content type. I tried using the method getPart("key") however an exception was thrown after accessing that method.
So, updating OKHttpClient to version 3.6 will allow me to use the FormBody class which sends request parameters with application/x-www-form-urlencoded content type. This way, the servlet side can now get the parameters via request.getParameter("key") method.
HTTP POST parameters are received in a Servlet via request parameters, not by reading the request body.

How to send HTTP request from android app to Heroku

I have a android app that uses the twilio sdk and is hosted by heroku server. I'm trying to push a button in my app to send a HTTP request to heroku to send a REST API request to Twilio to update my twiml URL. The current way i'm trying to send the the HTTP request is not working. I have looked through all of the examples that i could find and none of them show how to do this function. Does anybody know how to do this? Thanks in advance.
This is my code for trying to send the HTTP request to heroku
holdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yourappnamehere.herokuapp.com/hello");
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//setting a toast to see if this is being initiated
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
This is my updated code including the volley library
holdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setting up a request queue from Volley API
//RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
String url = "http://yourappnamehere.herokuapp.com/hello";
// Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
Toast.makeText(getBaseContext(), "why wont it work!", Toast.LENGTH_SHORT).show();
}
;
});
I would suggest using a library like Google Volley which is pretty slick
https://developer.android.com/training/volley/index.html
HttpRequest is deprecated from API level 22. It would be best practice to avoid using that. Use java.net.HttpUrlConnection instead.
However, if you still want to use it, the above code needs to be run on a thread other than the UI thread as mentioned in the comment above.

Java DefaultHttpClient HTTP PUT and Cookie

I'm send a request to YouTrack api to create issue.
String url = yBaseUrl + "/rest/issue?Task&"+ URLEncoder.encode(subject)+"&"+URLEncoder.encode(desc);
HttpClient client = new DefaultHttpClient();
HttpPut request = new HttpPut(url);
// add request header
((DefaultHttpClient) client).setCookieStore(cookie);
HttpResponse response = null;
//client.execute(post);
try {
response = client.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
} catch (IOException e) {
e.printStackTrace();
}
result - 403 code.
Why setCookieStore not working?
The problem was incorrect api url. Need use /rest/issue?project=Task&summary="+ URLEncoder.encode(subject)... The question is closed

Categories