I need to encode the params to ISOLatin which i intend to post to the site. I'm using org.apache.http. libraries. My code looks like follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("www.foobar.bar");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpParams params = new BasicHttpParams();
params.setParameter("action", "find");
params.setParameter("what", "somebody");
post.setParams(params);
HttpResponse response2 = httpClient.execute(post);
Thank you!
You are setting parameters wrong. Here is an example,
PostMethod method = new PostMethod(url);
method.addParameters("action", "find");
method.addParameters("what", "somebody");
int status = httpClient.executeMethod(method);
byte[] bytes = method.getResponseBody();
response = new String(bytes, "iso-8859-1");
if (status != HttpStatus.SC_OK)
throw new IOException("Status code: " + status + " Message: "
+ response);
The default encoding will be Latin-1.
Related
Whatever I try, twilio is not accepting my JSON request for making a call. I keep getting "No 'To' number is specified". I am sending this from Java. And we intentionally didn't want to use Twilio Rest library.
JSON Response:
{"code":21201, "message":"No 'To' number is specified", "more_info":"https://www.twilio.com/docs/errors/21201", "status":400}
JSON Request object
{"Url":"http://twimlets.com/echo?Twiml=%3CResponse%3E%3CSay+voice%3D%22alice%22+language%3D%22en-IN%22%3EImportant+alert%3APlease+check+your+SMS%3C%2FSay%3E%3C%2FResponse%3E","To":"%2B919900299477","From":"%2B919900299477","Method":"POST","FallbackMethod":"POST","StatusCallbackMethod":"POST","Record":"false"}
Here's the source code:
JSONObject jsonObject = new JSONObject();
jsonObject.put("Url", "http://twimlets.com/echo?Twiml=" + URLEncoder.encode(
"<Response><Say voice=\"alice\" language=\"en-IN\">"
+ psMessage + "</Say></Response>", "UTF-8"));
jsonObject.put("To", URLEncoder.encode(psNumberToCall, "UTF-8"));
jsonObject.put("From", URLEncoder.encode("+919988776655", "UTF-8"));
jsonObject.put("Method", "POST");
jsonObject.put("FallbackMethod", "POST");
jsonObject.put("StatusCallbackMethod", "POST");
jsonObject.put("Record", "false");
Log.i(getClass().getName(), "JSON Object: " + jsonObject.toString());
HttpClient httpClient = new DefaultHttpClient();
String sUrl = "https://api.twilio.com/2010-04-01/Accounts/AC****/Calls.json";
HttpPost httpPost = new HttpPost(sUrl);
StringEntity se = new StringEntity(jsonObject.toString());
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("content-type", "application/json");
String authString = "Basic " + Base64.encodeToString
((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", authString);
Log.i(getClass().getName(), "HttpPost: " + httpPost.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream is = httpResponse.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sbResp = new StringBuilder();
String sLine = "";
while((sLine = br.readLine()) != null){
sbResp.append(sLine);
}
is.close();
return sbResp;
I could solve this myself. Posting it for the benefit of others in case if they face the same problem:
The request is simple post method. Response can be JSON / XML etc.,
Here's the working code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(sTwilioUrl);
List<NameValuePair> paramsList = new ArrayList<NameValuePair>(3);
paramsList.add(new BasicNameValuePair("To", psNumberToCall));
paramsList.add(new BasicNameValuePair("From", "+919988776655"));
paramsList.add(new BasicNameValuePair("Url", sVoiceUrl));
httpPost.setEntity(new UrlEncodedFormEntity(paramsList));
//httpPost.setHeader("Accept", "application/json");
//httpPost.setHeader("content-type", "application/json");
String authString = "Basic " + Base64.encodeToString
((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
httpPost.setHeader("Authorization", authString);
HttpResponse httpResponse = httpClient.execute(httpPost);
return EntityUtils.toString(httpResponse.getEntity());
I'm working on simple client server communication using HttpPost. From the client side I'm setting a parameter(filename).
At the server side when I try to get the parameter value it's always showing null. I tried using MultiPartEntity but even that is not working.
Below is my client code:
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx:yyyy");
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(dataFile), -1);
reqEntity.setContentType("binary/octet-stream");
// Send in multiple parts if needed
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
//setting the parameter
httppost.getParams().setParameter("filename", "xxxx.xml");
HttpResponse response = httpclient.execute(httppost);
int respcode = response.getStatusLine().getStatusCode();
And this is my servlet code:
response.setContentType("binary/octet-stream");
Scanner scanner = new Scanner(request.getInputStream());
// reading the parameter
String filename = request.getParameter("filename");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\" + filename)));
Kindly let me know any possible solution for this issue.
Thanks in advance!
Ur setting parameters wrong... at the client side, do this:
ArrayList<NameValuePair> postParameters = postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("filename", "xxxx.xml");
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
curl -F file=#/path/to/index.html -u lslkdfmkls#gmail.com -F 'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps
I am trying to achieve the same using a java program using HttpClient library.
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("build.phonegap.com", 443, "https");
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort(),AuthScope.ANY_REALM),
new UsernamePasswordCredentials("abc#gmail.com", "abc123"));
String authToken = "?auth_token=abcdefgh";
HttpPost httpPost = new HttpPost("https://build.phonegap.com/api/v1/apps" + authToken );
String jsonString = "{\"title\":\"API V1 App\",\"create_method\":\"file\"}";
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart(new FormBodyPart("data", new StringBody(jsonString)));
multipartEntity.addPart("file", new FileBody(new File("C:/Users/Desktop/app.zip")));
/*StringEntity entity = new StringEntity(jsonString, "UTF-8"); */
httpPost.setEntity(multipartEntity);
System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
System.out.println(httpResponse.getStatusLine());
if(entity != null ){
System.out.println(EntityUtils.toString(entity));
}
In the above code I can only set StringEntity or FileEntity but not both and I think this is what is required to get the functionality of the curl command.
After trying with StringEntity and FileEntity I tried with MultipartEntity but no luck..
Can you please provide me with more details and if possible an example..
Thanks in advance.
One has to instantiate the MultipartEntity as follows:
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE
) ;
This worked for me.
By default the MultipartEntity is instantiated with HttpMultipartMode.STRICT mode which is documented in the javadocs as "RFC 822, RFC 2045, RFC 2046 compliant" .
Can someone brief out the RFC's mentioned here for clear understanding..
Thanks a Lot
Below is a snipped from a Java Client that connects to a website and uploads a file via the POST method. I have to reproduce this client in a Visual Studio environment, but I don't see any equivalent functions in the .NET environment for the setEntity() function used in the Java.
Everything I've found points to using this...
public void uploadFile(File uploadFile, String partner, String key,
String baseUrl,boolean isPartner) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1
);
String url = baseUrl + "?" + (isPartner ? "partnerId" : "ori") + "="
+ partner.toUpperCase() + "&authKey="
+ key+ "&key="
+ key;
HttpPost httppost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(uploadFile, "text/xml");
multipartEntity.addPart("dataFile", contentBody);
httppost.setEntity(multipartEntity);
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Everything I've found in Visual studio uses something like this below for the POST method. The WebRequest object has no obvious way of adding the parameters I need.
Dim request As WebRequest = WebRequest.Create("http://Test.com/import?partnerId=2&authKey=XdUa")
request.Method = "POST"
Dim postData As String = StrData
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "dataStr"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Any guidance would be greatly appreciated. If my question is not clear, let me know, I'll try again.
You can add following code snippet to add the parameter
request.ContentType="application/x-www-form-urlencoded"
Dim postData As String = "name1="+value1+"&name2="+value2
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Rest will remain same.
How to send Image or Video with post request with lot off other parameters with post request ? I have image and video in byte[] format and I am trying like
HttpClient httpClient = new DefaultHttpClient();
http.setURI(URI.create(url));
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(),
a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
http.setEntity(reqEntity);
HttpResponse response = httpClient.execute(http);
it pass through code but it doesn't upload anything ( bab !=null ). Does anybody have any idea what is wrong, I cannot provide more info, other team is at ws ?
Your code should look something more like this:
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(), a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
HttpPost postMethod = new HttpPost(url);
postMethod.setEntity(reqEntity);
HttpClient httpClient = new DefaultHttpClient():
HttpResponse response = httpClient.execute(postMethod);