So I have code that contstructs a HttpPost request like the following...
public LoginForm apa;
....
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
HttpParams httpparams = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(httpparams, schemeRegistry);
HttpClient httpclient = new DefaultHttpClient(mgr, httpparams);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for(String i : apa.getParams().keySet()){
nameValuePairs.add(new BasicNameValuePair(i, apa.getParams().get(i)));
}
List<NameValuePair> cookies = new ArrayList<NameValuePair>();
StringBuilder sb = new StringBuilder();
for(String i : apa.getCookies().keySet()){
sb.append(i);
sb.append("=");
sb.append(apa.getCookies().get(i));
sb.append(";");
}
// Trying to remove last ;
String cookie = sb.toString();
cookie = cookie.substring(0, cookie.length()-1);
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
httppost.setHeader("Cookie", cookie);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println(EntityUtils.toString(response.getEntity()));
It isn't logging in quite as I would expect so is there a way to output the entire request (headers and all) to match it up with the one I see in my Chrome Dev Tools? Am I over thinking this? Is there a form login library for Android or Java in general? Do I need content-length added?
Printing the headers is easy - you can list them using method getAllHeaders.
If you need to print HttpEntity, you can use method writeTo to write whole entity into ByteArrayOutputStream and create a String using toString.
Related
The AsyncHttpClient version is 1.4.7.
The server recieves the request, but could not find the file param
Working example
HttpClient httpclient;
HttpPost httppost;
httpclient = new DefaultHttpClient();
httppost = new HttpPost(URLRepo.URL_IMAGESAVE);
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_id", ""+deichapp.getInt("userid", 0)));
//.. add parameters
File file = new File(new URI(obj.getString("fileUri")));
nameValuePairs.add(new BasicNameValuePair("filename", file.getName()));
httpclient.getParams().setParameter("Connection", "Keep-Alive");
httpclient.getParams().setParameter("Content-Type", "multipart/form-data;");
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
for (BasicNameValuePair nameValuePair : nameValuePairs) {
entity.addTextBody(nameValuePair.getName(), nameValuePair.getValue());
}
entity.addPart("file", new FileBody(new File(new URI(obj.getString("fileUri")))));
httppost.setEntity(entity.build());
// Send and store the Image
HttpResponse response = httpclient.execute(httppost);
String json;
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
This uses the native android api and no external librarys like async http client. Make sure you execute this code on a background thread.
Try this:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("notes", "Test api support");
client.post(restApiUrl, params, responseHandler);
Hope this helps!
I am trying to do HTTP post request in a REST backend. The URL for the backend is using SSL therefore I have also added the necessary code to handle that. But I got the following response:
Cannot POST /api
Here is my code:
protected String doInBackground(String... args) {
try {
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
HttpPost post = new HttpPost("https://test-api.smart-trial.dk/api");
List <NameValuePair> nvps = new ArrayList <NameValuePair>(2);
nvps.add(new BasicNameValuePair("path[pathwayId]","5566e151817a62021b1ea809"));
nvps.add(new BasicNameValuePair("formData[firstname]","Name"));
nvps.add(new BasicNameValuePair("formData[lastname]","XXX"));
nvps.add(new BasicNameValuePair("formData[email]","example#mail.com"));
post.addHeader("Referer" ,"https://myurl.com/api");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
// get the response content as a string
String stringResponse = EntityUtils.toString(entity);
Log.d("Response", stringResponse);
}
Anything wrong in the code ? Or at least why do I get that response.
EDIT
I also have some rules for the paramaters.
"The post should be done with x-www-form-urlencoded body parameters"
I think more or less I over that by using post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); which x-www-form-urlencoded.
Parameters:
pathwayId (should be located in path)
firstname (should be located in formData)
lastname (should be located in formData)
email (should be located in formData)
Referer (Should be located in Header)
Sounds like your server is not configured to allow POST requests to that URL. But you need a way to verify that.
If you don't already have a REST testing plugin for your browser, find a plugin that will allow you to enter POST request data, download it and install it.
Then duplicate the POST data in the browser plugin, submit the request and view the response from the server.
At least this should help you figure out if the problem is in the app or in the server.
Trying to send file content to server from Android application like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
final InputStreamEntity reqEntity = new InputStreamEntity(
gdFileSystemDelegate.openFileInput(openFileInput(FilePath), -1);
reqEntity.setContentType("application/octet-stream");
httppost.setEntity(reqEntity);
httpClient.execute(httppost);
But its throws an exception:
cannot retry request with a non-repeatable request entity
What does it mean ? how to fix that ?
Try to set protocol param http.protocol.expect-continue to true in DefaultHttpClient:
#Override
protected HttpParams createHttpParams() {
HttpParams params = super.createHttpParams();
HttpProtocolParams.setUseExpectContinue(params, true);
return params;
}
I'm trying to post combination of string to my backend server. How can I achieve that using BasicNameValuePair. Here are some code which I was trying:
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost post = new HttpPost("API HERE");
List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password"));
I want to send username and password like:
username=USER&password=PWD
How to achieve the successful post to the server.
Help will be appreciated.
The following is what I use for all of my POST variables:
HttpParams httpParams = new BasicHttpParams();
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpPost httpPost;
httpPost = new HttpPost(Net_URL + Net_Get);
httpPost.setEntity(new UrlEncodedFormEntity(/*Name Value Pairs*/));
HttpResponse response = httpClient.execute(httpPost);
As a side suggestion, I would first do an some sort of encryption of a users password before sending it over the network, I have seen many who do not do this ^.^
I have implemented HTTP Post to post data to the backend. How do I implement HTTPS in Android (I have already configured the backend for https)?
I googled and found some solutions:
Secure HTTP Post in Android
and tried them but I do not receive any data in the backend.
Is it the correct way to implement? Is there any other method?
Below is my code snippet:
File file = new File(filepath);
HttpClient client = new DefaultHttpClient();
//String url = "http://test.....;
String url = "https://test......";
HttpPost post = new HttpPost(url);
FileEntity bin = new FileEntity(file, url);
post.setEntity(bin);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
Basically I am using fileentity to do a HTTPPost. Now I want to do this over https. After implementing https over at the backend I just modified http to https in the url and tested again. And it is not working.
Any idea how do i resolve this?
Thanks In Advance,
Perumal
Make sure your http client supports the SSL socket:
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
HttpParams params = new BasicHttpParams();
ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
HttpClient httpsClient = new DefaultHttpClient(manager, params);
and use this client to execute your POST request:
HttpPost post = new HttpPost("https://www.mysecuresite.com");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new StringEntity("This is the POST body", HTTP.UTF_8));
HttpResponse response = httpsClient.execute(post);