Sending Json POST to server using name value pair - java

I am sending Json Post request to server to through url: http://www.xyz.com/login
request structure:
{"requestdata":{"password":"abc","devicetype":"phone","username":"amrit#pqr.com","locale":"in"},"requestcode":10}
Code Snapshot:
MainActivity:
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("requestcode", "10"));
nameValuePair.add(new BasicNameValuePair("devicetype", "phone"));
nameValuePair.add(new BasicNameValuePair("locale", "in"));
nameValuePair.add(new BasicNameValuePair("username", "amrit#pqr.com"));
nameValuePair.add(new BasicNameValuePair("password", "abc"));
RestPost post = new RestPost(loginUrl, nameValuePair);
String Response = post.postData();
Log.i("Response:", Response);
RestPost class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class RestPost {
String url;
List<NameValuePair> nameValuePairs;
public RestPost(String str, List<NameValuePair> params) {
this.url = str;
this.nameValuePairs = params;
}
public String postData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(this.url);
StringBuilder builder = new StringBuilder();
try {
httppost.setEntity(new UrlEncodedFormEntity(this.nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.d("RestClient", "Status Code : " + statusCode);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return builder.toString();
}
}
But I'm not getting appropriate response, could anyone help me in sending appropriate format for getting server response. Thanks in advance.
Response which I'm getting:
{"error":{"resultCode":"400","status":"Invalid Request format"}}

You are currently sending the JSON in the form of
{
"requestcode": "10",
"devicetype": "phone",
"locale": "in",
"username": "amrit#pqr.com",
"password": "abc"
}
Which isn't the form the server is asking for. Try creating a string of the JSON you want to send. Then use:
httppost.setEntity(new StringEntity(jsonString, "UTF8"));
httppost.setHeader("Content-type", "application/json");
To send the string to the server.

I'm using AndroidHttpClient to post the request
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("User Agent");
URL urlObj = new URL(url);
HttpHost host = new HttpHost(urlObj.getHost(), urlObj.getPort(), urlObj.getProtocol());
AuthScope scope = new AuthScope(urlObj.getHost(), urlObj.getPort());
HttpContext credContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost (url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsArrayList));
// Execute post request and get http response
HttpResponse httpResponse = httpClient.execute(host, httpPost, credContext);
httpClient.close();
This works perfectly for me.

AndroidHttpClient http = AndroidHttpClient.new Instance("hai");

Related

Trying to submit android form data via PHP POST METHOD

I'm trying to create a form which is to send the information via a POST method.
public class PostData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yourdomain.com/serverside-script.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "01"));
nameValuePairs.add(new BasicNameValuePair("message", params[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
String op = EntityUtils.toString(response.getEntity(), "UTF-8");//The response you get from your script
return op;
} catch (IOException e) {
e.printStackTrace();
}
//reset the message text field
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
msgTextField.setText("");
Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
}
}
But I am getting errors when I try to import HttpClient, HttpPost, BaseNameValuePair etc....
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
Please help!!
HttpClient was deprecated in API Level 22 and removed in API Level 23. You have to use HttpURLConnection.
Docs how to use:-
https://developer.android.com/reference/java/net/HttpURLConnection
Example:-
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("id", "01")
.appendQueryParameter("message", params[0]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
But, If you still want to use it, then you need to add additional dependencies for it.
you need to use okhttp rather than http clinet
check here for okhttp post data.
https://www.studytutorial.in/android-okhttp-post-and-get-request-tutorial

Make an HttpPost with params and Body

I need to replicate a Postman POST in Java.
Usually I had to make an HttpPost with only params in URL, so it was easy to build:
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
But what I have to do if I have a POST like the image below where there are Params in URL and Body TOGETHER??
Now I'm making the HttpPost like this:
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("someUrls.com/upload");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", username));
postParameters.add(new BasicNameValuePair("password", password));
postParameters.add(new BasicNameValuePair("owner", owner));
postParameters.add(new BasicNameValuePair("destination", destination));
try{
post.setEntity(new UrlEncodedFormEntity(postParameters, Consts.UTF_8));
HttpResponse httpResponse = client.execute(post);
//Do something
}catch (Exception e){
//Do something
}
But how I put "filename" and "filedata" params in the Body together with the params in the URL?
Actually I'm using org.Apache library, but i could consider also others library.
Thanks to anybody that will help!
You can use below code to pass the body parameters as "application/x-www-form-urlencoded" in POST method call
package han.code.development;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpPost
{
public String getDatafromPost()
{
BufferedReader br=null;
String outputData;
try
{
String urlString="https://www.google.com"; //you can replace that with your URL
URL url=new URL(urlString);
HttpsURLConnection connection=(HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.addRequestProperty("Authorization", "Replace with your token"); // if you have any accessToken to authorization, just replace
connection.setDoOutput(true);
String data="filename=file1&filedata=asdf1234qwer6789";
PrintWriter out;
if((data!=null))
{
out = new PrintWriter(connection.getOutputStream());
out.println(data);
out.close();
}
System.out.println(connection.getResponseCode()+" "+connection.getResponseMessage());
br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb=new StringBuilder();
String str=br.readLine();
while(str!=null)
{
sb.append(str);
str=br.readLine();
}
outputData=sb.toString();
return outputData;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
public static void main(String[] args)
{
HttpPost post=new HttpPost();
System.out.println(post.getDatafromPost());
}
}
I think this question, and this question are about similar issues and both have good answers.
I would recommend using this library as it is well maintained and simple to use if you want.
I've resolved making this way:
put on POST URL header params;
adding as MultipartEntity the filename and filedata.
Here the code....
private boolean uploadQueue(String username, String password, String filename, byte[] fileData)
{
HttpClient client = HttpClientBuilder.create().build();
String URL = "http://post.here.com:8080/";
HttpPost post = new HttpPost(URL +"?username="+username+"&password="password);
try
{
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addBinaryBody("filedata", fileData, ContentType.DEFAULT_BINARY, filename);
entityBuilder.addTextBody("filename", filename);
post.setEntity(entityBuilder.build());
HttpResponse httpResponse = client.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
logger.info(EntityUtils.toString(httpResponse.getEntity()));
return true;
}
else
{
logger.info(EntityUtils.toString(httpResponse.getEntity()));
return false;
}
}
catch (Exception e)
{
logger.error("Error during Updload Queue phase:"+e.getMessage());
}
return false;
}

JAVA Http POST request in UTF-8

My J2EE application is able to receive POST request from a JSP page, no problem about that.
But if I use another java application to send a POST request, the parameter received is not an UTF-8 string.
Here there is my code:
URL url = new URL("http://localhost:8080/ITUNLPWebInterface/SimpleApi");
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoInput(true);
cox.setDoOutput(true);
cox.setRequestMethod("POST");
cox.setRequestProperty("Accept-Charset", "UTF-8");
cox.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "UTF-8");
DataOutputStream dos = new DataOutputStream(cox.getOutputStream());
String query = "tool=ner&input=şaşaşa";
dos.writeBytes(query);
dos.close();
Am I doing something wrong?
Thanks for your reply
this work!!!.
package com.erenerdogan.utils;
import com.erenerdogan.webservice.ServiceInterface;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
/**
*
* #author erenerdogan
*/
public class WebService
{
private String server;
public WebService(String server) {
this.server = server;
}
private HttpPost createPostRequest(String method, Map<String, String> paramPairs){
// Creating HTTP Post
HttpPost httpPost = new HttpPost(server + "/" + method);
// Building post parameters
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(paramPairs.size());
for (String key : paramPairs.keySet()){
nameValuePair.add(new BasicNameValuePair(key, paramPairs.get(key)));
System.out.println("Key : "+ key + " - Value : "+ paramPairs.get(key) );
}
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
return httpPost;
}
public String callServer(String method, Map<String, String> paramPairs) throws ClientProtocolException, IOException{
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
HttpParams httpParameters = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 3 * 1000);
HttpResponse httpResponse = httpClient.execute(createPostRequest(method, paramPairs));
HttpEntity httpEntity = httpResponse.getEntity();
String xml = EntityUtils.toString(httpEntity);
return xml;
}
}
The docs for DataOutputStream.writeBytes(String) says
Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits. If no exception is thrown, the counter written is incremented by the length of s.
Instead use cox.getOutputStream().write(query.getBytes("UTF-8"));
DataOutputStream is redundant here.
try this
HttpClient client = new DefaultHttpClient();
HttpPost port = new HttpPost("http://localhost:8080/ITUNLPWebInterface/SimpleApi");
List<NameValuePair> parameters = new ArrayList<NameValuePair>(3);
parameters.add(new BasicNameValuePair("tool", "ner"));
parameters.add(new BasicNameValuePair("input", "şaşaşa"));
//post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
post.setEntity(new UrlEncodedFormEntity(params, "ISO-8859-3")); //try this one
HttpResponse resp = client.execute(post);
https://en.wikipedia.org/wiki/ISO/IEC_8859-3 seem to support your spechial character ş
It works form me:
connection = (HttpURLConnection) url.openConnection();
...
byte[] data = message.getBytes("UTF-8");
...
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.write(data);
wr.close();
a) "application/x-www-form-urlencoded" doesn't have a charset parameter; it's essentially limited to ASCII
b) to send non-ASCII characters, you need to encode them in UTF-8 (not the client's default encoding) and percent-escape them; see http://www.w3.org/TR/2014/REC-html5-20141028/forms.html#application/x-www-form-urlencoded-encoding-algorithm for the details.
base on HttpClient's Example "FluentRequests.java":
Content content = Request.Post("http://localhost:8080/ITUNLPWebInterface/SimpleApi")
.body(new UrlEncodedFormEntity(
Form.form()
.add("tool", "ner")
.add("input", "şaşaşa")
.build(), "UTF-8"))
.execute().returnContent();
System.out.println(content);

How to add,set and get Header in request of HttpClient?

In my application I need to set the header in the request and I need to print the header value in the console...
So please give an example to do this the HttpClient or edit this in my code...
My Code is ,
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class SimpleHttpPut {
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://http://localhost:8089/CustomerChatSwing/JoinAction");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("userId",
"123456789"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks in advance...
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
On apache page: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
You have something like this:
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):
public class App {
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpClients.custom().build();
// (1) Use the new Builder API (from v4.3)
HttpUriRequest request = RequestBuilder.get()
.setUri("https://api.github.com")
// (2) Use the included enum
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
// (3) Or your own
.setHeader("Your own very special header", "value")
.build();
CloseableHttpResponse response = client.execute(request);
// (4) How to read all headers with Java8
List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
httpHeaders.stream().forEach(System.out::println);
// close client and response
}
}

HttpPost not accepting lengthy url in Java

Here is my httppost method from my android app. It is not accepting lenthy urls. There is no reponse/exception for lengthy urls. When I enter the same url manually in browser it works fine. Can anyone point out the issue here?
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Update:
Added one sample url. The same url works fine when manually entered in browser and it gives response.
url.com/data?format=json&pro={%22merchanturl%22:%22http://url.com/logo.pn‌​g%22,%22price%22:599,%22productDesc%22:%22Apple%2032GBBlack%22,%22prodID%22:%2291‌​3393%22,%22merchant%22:%224536%22,%22prourl%22:%22http://url.com/data%22,%22name%‌​22:%22Apple%2032GB%20%2D%20Black%22,%22productUrl%22:%22http://www.url.com/image.‌​jpg%22,%22myprice%22:550,%22mercname%22:%22hello%22,%22mybool%22:false}
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
I suppose your URL contains things like index.php?call=getUsers&something=bla
To solve this you can make use of NameValuePair :
String url = "http://example.com/index.php";
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("call", "getUsers"));
nvp.add(new BasicNameValuePair("something", "bla"));
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
[...]
} catch (Exception e) {
[...]
}
you can try with the following code. you sould have Json API.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
System.out.println(json.toString());
System.out.println(json.get("id"));
}

Categories

Resources