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
Related
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;
}
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");
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);
I'm trying to do example form: http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html
I've got everything allright with android app (I think), but to simulate the
server i all the time got error 403.
The code is the same like in example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class AuthenticationUtil
{
private AuthenticationUtil()
{
}
public static String getToken(String email, String password)
throws IOException {
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(email);
builder.append("&Passwd=").append(password);
builder.append("&accountType=GOOGLE");
builder.append("&source=CloudTut");
builder.append("&service=ac2dm");
// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = con.getOutputStream();
output.write(data);
output.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String line = null;
String auth_key = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Auth=")) {
auth_key = line.substring(5);
}
}
// Finally get the authentication token
// To something useful with it
return auth_key;
}
}
and the error respond:
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.com/accounts/ClientLogin
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1436)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at AuthenticationUtil.getToken(AuthenticationUtil.java:48)
at GetAuthenticationToken.main(GetAuthenticationToken.java:8)
This code is from a functioning app and works well for me. It uses the C2DM account login details to request an auth-token, which can then be used to send C2DM messages to client devices. Note that this code is from an Android app, but would typically be executed on the server.
public static String getClientLoginAuthToken() {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", "C2DMEMAILADDRESS));
nameValuePairs.add(new BasicNameValuePair("Passwd", "C2DMPASSWORD));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
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) {
Trace.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
return line.substring(5);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Trace.e(TAG, "Failed to get C2DM auth code");
return "";
}
If you continue to have problems, then best to assume the C2DM account wasn't set up right, and create another one.
I am currently trying to authenticate with a server via a http Get call. The code provided below works when compiled in a java project. Returning the correct token to the program. However whenever I try to implement the same code in Android I do not get a token returned via the Get call.
In Android I am returning inputLine in a function, however inputLine is always an empty string.
The system.out.println() prints the returned token.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class JavaHttpsExample
{
public static void main(String[] args)
{ String inputLine = new String();
try
{
String httpsURL = "https://the url";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr=new InputStreamReader(ins);
BufferedReader in =new BufferedReader(isr);
inputLine = in.readLine();
System.out.println(inputLine);
in.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
thanks for your help!!!
You probably did not add the Internet-Permission to your projects AndroidManifest.xml.
If so, add the following line as a child of the <manifest/> node:
<uses-permission android:name="android.permission.INTERNET" />
I'm using POST and FormEntity for retrieving data from the server (such as authentication), and i have never had any problems:
final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);
//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);
//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]
maybe you'll find this usefull