HTTP POST request in JAVA with payload as a json file - java

Below is what i tried to send a HTTP POST request which send the json file as payload. The Error I always get is
java.io.FileNotFoundException: test.json (The system cannot find the file specified)
Although the test.json file is in the same folder.
private void sendPost() throws Exception {`
String url = "url";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String postData = AutomaticOnboarding.readFile("test.json");
urlParameters.add(new BasicNameValuePair("data", postData));
StringEntity se = new StringEntity(postData);
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
post.setEntity(se);
HttpResponse response = httpClient.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code : " +responseCode);
if(responseCode == 200){
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
}
Here follows the readFile method:
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}

Use the class loader to get resources inside the jar
getClass().getClassLoader().getResourceAsStream(filename)

Related

Send List as basic name value pair as HttpPost in restful web service

I am trying to do an httpPost into a webservice. I want to send a list as an array. Here is what I 've done so far.
public Response searchMessages(#QueryParam("tags") List<String> tags, #QueryParam("senders") List<String> senders, #QueryParam("api_keys") List<String> apiKeys) throws Exception
{Iterator<String> tagsIt = tags.iterator();
Iterator<String> sendersIt = senders.iterator();
Iterator<String> apiKeysIt = apiKeys.iterator();
CloseableHttpClient httpClient = null;
HttpPost httpPost =null;
List<NameValuePair> nvps=null;
CloseableHttpResponse response=null;
InputStream in=null;
String myResponse = "";
try
{
httpClient = HttpClients.createDefault();
httpPost = new HttpPost(url);
while(tagsIt.hasNext())
{
String keyIt = tagsIt.next();
nvps.add(new BasicNameValuePair("tags",hashMap.get(keyIt)));
}
while(sendersIt.hasNext())
{
String keySend = sendersIt.next();
nvps.add(new BasicNameValuePair("senders",hashMap.get(keySend)));
}
while(apiKeysIt.hasNext())
{
String keySend = sendersIt.next();
nvps.add(new BasicNameValuePair("apiKeys",hashMap.get(keySend)));
}
//System.out.println(key+" "+hashMap.get(key));
httpPost.setEntity(new UrlEncodedFormEntity(nvps,Consts.UTF_8));
response = httpClient.execute(httpPost);
BufferedReader buffer=null;
try{
//System.out.println(response.toString());
in= response.getEntity().getContent();
buffer = new BufferedReader(new InputStreamReader(in));
String s = "";
while ((s = buffer.readLine()) != null) {
myResponse += s+"\n";
}
status= response.getStatusLine().getStatusCode();
resp = Response.status(status).entity(myResponse).build();
}
catch(Exception e)
{
e.printStackTrace();
}
}
finally
{
in.close();
response.close();
httpClient.close();
}
My issue is that I get a null pointer exception in in.close() line.
I do not know where my mistake is.Please help.

In CKAN, I am trying to upload a file using java client.But getting error code "400" but not showing any error log

In CKAN, I am trying to upload a file using java client.But getting error code "400" but not showing any error log. I have done CKAN setup locally on Centos7 system. Please help if any suggestion, thanks :)
protected String MultiPartPost(String path, String data)
throws CKANException {
String body = "";
String CKANrepos = "http://172.21.9.118:5000";
String CKANapiHeader="X-CKAN-API-Key";
String CKANapi = "api key";
//1st part
String generatedFilename=null;
HttpClient httpclient = new DefaultHttpClient();
String filename = "test.txt";
try {
// create new identifier for every file, use time
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyyMMMddHHmmss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date=dateFormatGmt.format(new Date());
generatedFilename=date +"/"+filename;
HttpGet getRequest = new HttpGet(this.CKANrepos+ "/api/storage/auth/form/"+generatedFilename);
getRequest.setHeader(CKANapiHeader, this.CKANapi);
HttpResponse response = httpclient.execute(getRequest);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode!=200){
throw new IllegalStateException("File reservation failed, server responded with code: "+statusCode+
"\n\nThe message was: "+body);
}
}catch (IOException ioe) {
System.out.println(ioe);
} finally {
httpclient.getConnectionManager().shutdown();
}
//2nd part
File file = new File("D:\\test.txt");
httpclient = new DefaultHttpClient();
try {
FileBody bin = new FileBody(file,"text/html");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", bin);
reqEntity.addPart("key", new StringBody(generatedFilename));
HttpPost postRequest = new HttpPost(this.CKANrepos+"/storage/upload_handle");
postRequest.setEntity(reqEntity);
postRequest.setHeader(CKANapiHeader, this.CKANapi);
HttpResponse response = httpclient.execute(postRequest);
int statusCode = response.getStatusLine().getStatusCode();
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String line;
while ((line = br.readLine()) != null) {
body += line;
}
if(statusCode!=200){
System.out.println("statusCode ==" +statusCode);
}
}catch (IOException ioe) {
System.out.println(ioe);
} finally {
httpclient.getConnectionManager().shutdown();
}
return body;
}
}

HTTP/1.1 400 Bad Request Apache

I'm attempting to login to twitter using the following code I've written. The issue is on each execution i receive a 400 Bad Request back as the response. I have tried numerous attempts to get this to work to no avail.
public void login(String url) throws ClientProtocolException, IOException{
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add request header
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// set cookies
setCookies(response.getFirstHeader("Set-Cookie") == null ? "" : response.getFirstHeader("Set-Cookie").toString());
Document doc = Jsoup.parse(result.toString());
System.out.println(doc);
// Get input elements
Elements loginform = doc.select("div.clearfix input[type=hidden][name=authenticity_token]");
String auth_token = loginform.attr("value");
System.out.println("Login: "+auth_token);
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("authenticity_token", auth_token));
paramList.add(new BasicNameValuePair("session[username_or_email]", "twitter_username"));
paramList.add(new BasicNameValuePair("session[password]", "twitter_password"));
System.out.println(paramList);
HttpPost post = new HttpPost(url);
// add header
post.setHeader("Host", "twitter.com");
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Accept", "text/html,application/xhtml;q=0.9,*/*;q=0.8");
post.setHeader("Accept-Language", "en-US,en;q=0.5");
post.setHeader("Keep-Alive", "115");
post.setHeader("Cookie", getCookies());
post.setHeader("Connection", "keep-alive");
post.setHeader("Referer", "https://twitter.com/");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(paramList));
// Execute POST data
HttpResponse res = client.execute(post);
int responseCode = res.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + paramList);
System.out.println("Response Code : " + responseCode);
System.out.println("Headers: "+res.getAllHeaders().toString());
System.out.println("Response: "+res.getStatusLine());
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(res.getEntity().getContent()));
StringBuffer resul = new StringBuffer();
String line1 = "";
while ((line1 = rd1.readLine()) != null) {
resul.append(line1);
}
Document doc2 = Jsoup.parse(res.toString());
System.out.println(doc2);
}
public static void main(String[] args) throws ClientProtocolException, IOException{
Browser b = new Browser();
b.login("https://twitter.com/login");
}
I believe that everything that needs to be POST'd is being, such as the username, password, as well as the authenticity token.
Turns out i was sending the wrong session information in my POST request! If anyone else has a similar issue i recommend using Chrome Developer tools to inspect the headers being sent/received.

HttpResponse and BufferedReader

I am trying to read the buffer (android application) and set the value to my TextView 'httpStuff'. But i dont think i am getting some response from the URI.
I don't get any runtime errors. I tried many flavour of the same logic. Nothing seems to be working.
INTERNET permission is already set in the manifest. SdkVersion="15". Any help ?
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
httpStuf.setText( in.readLine());
I think you are missing the while loop and also, when you say only in.readLine(), may be it is returning you an empty line from the response, though it is having enough data.So make sure to read the reader entirely like this and check its contents.
while ((line = rd.readLine()) != null) {
httpStuf.setText(line+"\r\n");
}
Hope this will help you.
This code worked for me
InputStream is = response.getEntity().getContent();
String strResponse = inputStreamToString(is);
private String inputStreamToString(InputStream is)
{
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 1024 * 4);
// Read response until the end
try
{
while ((line = rd.readLine()) != null)
{
total.append(line);
}
} catch (IOException e)
{
Log.e(TAG, "error build string" + e.getMessage());
}
// Return full string
return total.toString();
}
try to get the status code of response and Then you can compare with the (HTTP status)
int responseCode=response.getStatusLine().getStatusCode()
I am using this method to simply catch the HTTP response and it works fine for me.
public String httpGetResponse(String url) {
try {
Log.i("HTTP Request", "httpGet Request for : " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
//get.setHeader("Connection", "keep-alive");
HttpResponse response = client.execute(get);
InputStream is = response.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
str.append(line + "\n");
}
return str.toString();
} catch (Exception e) {
Log.e("HTTP error", "Error in function httpGetResponse : "
+ e.getMessage());
return null;
}
}

Post url from android to retrieve data

i have a url "http://184.82.158.234/~store/rest/system/connect.json" and posting this url with mozilla addon called poster returns data in form of json
what i want is to post this url from android to get that json data into androids view .
any help is highly appreciated
thanks
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
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
}
}
response variable will contain your json data.
Here is a function maybe you can use to post a string to a URL.
public String doHttpPost(final String fullUrl, final String body) {
final URL url = new URL(fullUrl);
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// set the request mode as POST
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-charset", "utf-8");
urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
// write the body.
request.writeBytes(body);
// flush output buffer
request.flush();
request.close();
// construct a read using input stream and charset.
final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
final BufferedReader in = new BufferedReader(isr);
String inputLine;
final StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine).append("\n");
}
in.close();
isr.close();
urlConnection.disconnect();
return stringBuilder.toString();
}
check below code: try this it may help you.
ArrayList nameValuePairs1 = new ArrayList();
nameValuePairs1.add(new BasicNameValuePair("user_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_id", ""));
nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = entity.getContent();
BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(bufr.readLine() + "\n");
String line = "0";
while ((line = bufr.readLine()) != null)
{
sb.append(line + "\n");
}
is1.close();
result = sb.toString();
result is a json String. parse that json and display in any control. i displaied that in text view see below.
final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (Name.length() > 0 && Name != null) {
txtvenue.setText(Name);
} else {
txtvenue.setText(venue_name);
}
}
};
new Thread() {
public void run() {
try {
// put your result here
JSONObject jObject = new JSONObject(result);
JSONObject menuObject = jObject.getJSONObject("response");
JSONObject venueObject = menuObject.getJSONObject("venue");
Name = venueObject.getString("name");
String id = venueObject.getString("id");
Log.d("--------name---------", Name);
Log.d("--------id---------", id);
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();

Categories

Resources