Unable to receive any request from MSTeams to my endpoint - java

I created a bot using Bot Channels Registration and integrated it with the MSTeams channel. But when I send a message from Teams, I did not receive any request from the Teams to my Message Endpoint.
Please help me to resolve with this.
Please try using this.
TestSample.java
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
#WebServlet("/MSTeamsServlet/api/messages")
public class TestSample extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestSample() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletInputStream st = request.getInputStream();
JSONObject inputjson = new JSONObject();
JSONParser parser = new JSONParser();
String inputJson ="";
try {
BufferedInputStream bin = new BufferedInputStream(st);
int ch;
inputJson= "";
while ((ch = bin.read()) != -1) {
inputJson = inputJson+(char)ch;
}
} catch (Exception e) {
e.printStackTrace();
}
String result = "";
System.out.println("INSIDE MS TEAMS SERVLET:::");
System.out.println("REQUEST:"+inputJson);
JSONObject json = new JSONObject();
JSONParser parse = new JSONParser();
JSONObject requestBody = new JSONObject();
TestRequest client = new TestRequest();
try
{
requestBody = (JSONObject)parse.parse(inputJson);
JSONObject conversation = (JSONObject) requestBody.get("conversation");
String id = requestBody.get("id").toString();
String serviceUrl = requestBody.get("serviceUrl").toString();
String conversationId = conversation.get("id").toString();
JSONObject from = (JSONObject) requestBody.get("from");
JSONObject recepient = (JSONObject) requestBody.get("recipient");
String url = serviceUrl+"v3/conversations/"+conversationId+"/activities/"+id;
String userId = "";
String aadObjectId = from.get("aadObjectId").toString();
json.put("text", "Hai! How can I help you!!!");
json.put("type", "message");
json.put("from", recepient);
json.put("conversation", conversation);
json.put("recipient", from);
json.put("replyToId", id);
result = client.hitPOSTAPI(url, "POST", json);
System.out.println(result);
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
TestRequest.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.Charsets;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.io.CharStreams;
public class TestRequest {
static String microsoft_AppID = "REPLACE YOUR APP_ID";
static String microsoft_AppPwd = "REPLACE YOUR APP_PASSWORD";
public static String hitPOSTAPI(String urlString, String methodType, JSONObject postParameter) {
String result = "";
try {
HttpPost post = new HttpPost(urlString);
StringEntity params = new StringEntity(postParameter.toString());
System.err.println(postParameter.toString());
post.addHeader("content-type", "application/json");
post.addHeader("Authorization", "Bearer "+generateToken());
post.setEntity(params);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20 * 1000).setConnectionRequestTimeout(20*1000).setSocketTimeout(100*1000).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
HttpResponse response = httpClient.execute(post);
InputStream in = null;
if (response.getStatusLine().getStatusCode()==200 &&response != null) {
in = response.getEntity().getContent();
result = CharStreams.toString(new InputStreamReader(
in, Charsets.UTF_8));
}
post.abort();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
}
return result;
}
public static String generateToken() {
String token = "";
URL url = null;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL("https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Host", "login.microsoftonline.com");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
OutputStream wr = urlConnection.getOutputStream();
String credentials = "grant_type=client_credentials&client_id="+microsoft_AppID+"&client_secret="+microsoft_AppPwd+"&scope=https://api.botframework.com/.default";
wr.write(credentials.toString().getBytes());
wr.flush();
wr.close();
if(urlConnection.getResponseCode()==200)
{
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject)parser.parse(sb.toString());
token = obj.get("access_token").toString();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
urlConnection.disconnect();
}
return token;
}
}
Please check this are you able to get any idea. As for MSTeams only my endpoint is not working..If I check it through NGROK it is working.

Related

How to perform post request in header and body in JSON

I'm using JSON and want to send post request to server via username, password in body and x-auth-app-id, x-auth-app-hash in header..
I have test on Postmen and it return 200 (status ok), But when I build my sources it happen error.
This is my class header:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import net.sf.json.JSONObject;
public class HttpRequestUtil {
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
InputStream inputStream=null;
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestProperty("x-auth-app-id", "6166611659356156223");
httpUrlConn.setRequestProperty("x-auth-app-hash", "a44f4ea21475fa6761392ba4bc659990bee771c413b2c207490a79f9ec78c2a61234");
httpUrlConn.setRequestProperty("Content-Type", "application/json");
httpUrlConn.setRequestMethod(requestMethod);
if ("POST".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}
catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("Our server connection timed out");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("https request error:{}");
}
finally {
try {
if(inputStream!=null) {
inputStream.close();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsonObject;
}
}
And class Body:
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class CallCenterController {
public static void main(String[] args) throws JSONException {
String sipUser = "vchi_dd";
String sipPassword = "m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa";
Map<String, Object> sipAccount = new HashMap<String, Object>();
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);
sipAccount = postData(sipUser, sipPassword);
System.out.println("result: " + sipAccount);
};
public static JSONObject postData(String sipUser, String sipPassword) {
String url="https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser="+sipUser+"&sipPassword="+sipPassword;
return HttpRequestUtil.httpRequest(url, "POST", "");
}
}
When I build it happen an exception following as:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://myservice.com/oapi/v1/call/click-to-call/02437590555&sipUser=vchi_dd&sipPassword=m9Bp7s+CtQj85HygnIFjPn7O4Vithrunaa
https request error:{}
result: null
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at com.mypackage.HttpRequestUtil.httpRequest(HttpRequestUtil.java:63)
at com.mypackage.CallCenterController.postData(CallCenterController.java:45)
at com.mypackage.CallCenterController.main(CallCenterController.java:34)
How to send correct data to my url and fix the problem?
I would use Java HTTP Client API if your java version is high enough.
Here's a link to it https://www.baeldung.com/java-9-http-client
I have used it and it feels more maintainable and clear.
Also, it seems that you're sending the request with empty body even though you say in your question that you are sending username and password in body.
And why are you adding username and password to a map if you are not using the map?
sipAccount.put("sipUser", sipUser);
sipAccount.put("sipPassword", sipPassword);

503 Service unavailable while uploading file on SharePoint online in Finish Upload method

I am trying to upload the file on SharePoint larger than 250MB. I have divided data of the file in small chunks say 100MB and used Start upload, continue Upload and Finish Upload of SharePoint. I am getting 503 service unavailable in finish upload method if my file size is 250MB or greater. However, The below code runs successfully for the file size up to 249MB. Any leads or help is much appreciated.
Thanks,
Bharti Gulati
package test;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class SampleFileUpload1 {
private final static int chunkSize = 100 * 1024 * 1024;
public static void main(String args[]) throws IOException {
SampleFileUpload1 fileUpload = new SampleFileUpload1();
File file = new File("C:\\users\\bgulati\\Desktop\\twofivefive.txt");
fileUpload.genereateAndUploadChunks(file);
}
private static void executeRequest(HttpPost httpPost, String urlString) {
try {
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
System.out.println("Response getReasonPhrase: " + response.getStatusLine().getReasonPhrase());
System.out.println("Response getReasonPhrase: " + response.getEntity().getContent().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while (true) {
String s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void executeMultiPartRequest(String urlString, byte[] fileByteArray) throws IOException {
HttpPost postRequest = new HttpPost(urlString);
postRequest = addHeader(postRequest, "accessToken");
try {
postRequest.setEntity(new ByteArrayEntity(fileByteArray));
} catch (Exception ex) {
ex.printStackTrace();
}
executeRequest(postRequest, urlString);
}
private static HttpPost addHeader(HttpPost httpPost, String accessToken) {
httpPost.addHeader("Accept", "application/json;odata=verbose");
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setHeader("Content-Type", "application/json;odata=verbose;charset=utf-8");
return httpPost;
}
private static String getUniqueId(HttpResponse response, String key) throws ParseException, IOException {
if (checkResponse(response)) {
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
JSONObject json = new JSONObject(responseString);
return json.getJSONObject("d").getString(key);
}
return "";
}
private static boolean checkResponse(HttpResponse response) throws ParseException, IOException {
if (response.getStatusLine().getStatusCode() == 200 || (response.getStatusLine().getStatusCode() == 201)) {
return true;
}
return false;
}
private String createDummyFile(String relativePath, String fileName) throws ClientProtocolException, IOException {
String urlString = "https://siteURL/_api/web/GetFolderByServerRelativeUrl('"+relativePath+"')/Files/add(url='" +fileName+"',overwrite=true)";
HttpPost postRequest = new HttpPost(urlString);
postRequest = addHeader(postRequest, "access_token");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(postRequest);
return getUniqueId(response, "UniqueId");
}
private void genereateAndUploadChunks(File file) throws IOException {
String relativePath = "/relativePath";
String fileName = file.getName();
String gUid = createDummyFile(relativePath, fileName);
String endpointUrlS = "https://siteURL/_api/web/GetFileByServerRelativeUrl('"+relativePath+"/"+fileName+"')/savebinarystream";
HttpPost postRequest = new HttpPost(endpointUrlS);
postRequest = addHeader(postRequest, "access_token");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(postRequest);
long fileSize = file.length();
if (fileSize <= chunkSize) {
}
else {
byte[] buffer = new byte[(int) fileSize <= chunkSize ? (int) fileSize : chunkSize];
long count = 0;
if (fileSize % chunkSize == 0)
count = fileSize / chunkSize;
else
count = (fileSize / chunkSize) + 1;
// try-with-resources to ensure closing stream
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bytesAmount = 0;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = 0;
String startUploadUrl = "";
int k = 0;
while ((bytesAmount = bis.read(buffer)) > 0) {
baos.write(buffer, 0, bytesAmount);
byte partialData[] = baos.toByteArray();
if (i == 0) {
startUploadUrl = "https://siteURL/_api/web/GetFileByServerRelativeUrl('"+relativePath+"/"+fileName+"')/StartUpload(uploadId=guid'"+gUid+"')";
executeMultiPartRequest(startUploadUrl, partialData);
System.out.println("first worked");
// StartUpload call
} else if (i == count-1) {
String finishUploadUrl = "https://siteURL/_api/web/GetFileByServerRelativeUrl('"+relativePath+"/"+fileName+"')/FinishUpload(uploadId=guid'"+gUid+"',fileOffset="+i+")";
executeMultiPartRequest(finishUploadUrl, partialData);
System.out.println("FinishUpload worked");
// FinishUpload call
} else {
String continueUploadUrl = "https://siteURL/_api/web/GetFileByServerRelativeUrl('"+relativePath+"/"+fileName+"')/ContinueUpload(uploadId=guid'"+gUid+"',fileOffset="+i+")";
executeMultiPartRequest(continueUploadUrl, partialData);
System.out.println("continue worked");
}
i++;
}
}
}
}
}

HttpURLConnection working in Java but not android

We've been trying to send a POST request to a node.js server in an android app. Because the old apache dependencies are deprecated (and I can't seem to access them - I've tried) we've been using the HttpURLConnection classes. We've coded a class in java that works as just a standalone class (Request.java) but when incorperated in the android program, it throws an error every time and when trying to get the message of the error, it just returns null.
Request.java
package andrewmmattb.beacongame;
/**
* Created by matt on 05/03/2016.
*/
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Request {
public static void main(String[] args) throws Exception {
Request http = new Request();
System.out.println("POST");
http.sendPost("{\"username\": \"matt\",\"newPoints\":5}");
}
public static void sendPost(String json) throws Exception {
String url = "http://ec2-54-187-69-193.us-west-2.compute.amazonaws.com/points";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
GameActivity.java
package andrewmmattb.beacongame;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Base64;
import android.util.JsonWriter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import org.json.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class GameActivity extends Activity {
String username;
String serverPath = "THE PATH TO THE SERVER";
int score = 0;
int prevScore = 0;
TextView usernameTextView;
TextView scoreTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
usernameTextView = (TextView)findViewById(R.id.textViewGameUsername);
scoreTextView = (TextView)findViewById(R.id.textViewGameScore);
Intent intent = getIntent();
username = intent.getStringExtra("username");
usernameTextView.setText(username);
try {
makeSeverPost();
}
catch (IOException e) {
Toast.makeText(GameActivity.this,"There was an IO error, called after function call (line 56)",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
void makeSeverPost() throws IOException {
// creates a map object with username and the additional points to the previous sent score
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
// sets the previous score to equal the current score
prevScore = score;
// writes the map into a string in JSON format
String jsonString = new JSONObject(values).toString();
try {
Request.sendPost(jsonString);
} catch (Exception e) {
e.printStackTrace();
Log.e("problem",""+e.getMessage());
}
}
}
There are many redundant dependancies due to all the other attempts to do this we've made.
In android network on main thread are not allowed.
You have to call this method from an AsyncTask.
Example:
class MakeSeverPostTask extends AsyncTask<Void, String, JSONObject>
{
Map<String,Object> params;
public MakeSeverPostTask(Map<String,Object> params){
this.params = params;
}
protected JSONObject doInBackground(Void... v)
{
String jsonString = new JSONObject(this.params).toString();
return Request.sendPost(jsonString);
}
protected void onPostExecute(JSONObject result)
{
}
}
Usage:
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
new MakeSeverPostTask(values).execute();
Here is more elaborated solution:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
usernameTextView = (TextView)findViewById(R.id.textViewGameUsername);
scoreTextView = (TextView)findViewById(R.id.textViewGameScore);
// creates a map object with username and the additional points to the previous sent score
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
// writes the map into a string in JSON format
String jsonString = new JSONObject(values).toString();
String url = "http://ec2-54-187-69-193.us-west-2.compute.amazonaws.com/points";
// executing AsyncTask with passing string parameters.
ServerAsyncTask makeServerPost = new ServerAsyncTask();
makeServerPost.execute(url, jsonString);
}
private class ServerAsyncTask extends AsyncTask<String, Void, JSONObject> {
private final String TAG = ServerAsyncTask.class.getSimpleName();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
URL obj = new URL(params[0]); // added url
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params[1]); // Added json
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.i(TAG, "\nSending 'POST' request to URL : " + params[0]);
Log.i(TAG, "Post parameters : " + urlParameters);
Log.i(TAG, "Response Code : " + responseCode);
// safer way to parse response
if(responseCode == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.i(TAG, response.toString());
result = new JSONObject(response.toString());
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
/* You get response jsonObject here,
you can now update your UI here*/
// Example update your score.
try {
String score = (String) jsonObject.get("score");
scoreTextView.setText(score);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

HttpEntity alternate in android?

For the purpose of uploading images, I am using the android volley library to send multipart requests to a server. I have written some custom code for the android Volley library.HtppEntity is used here as a class in this file, but now I am getting a warning that HttpEntity is deprecated. I happen to know that HttpurlConnection is an alternative, but I don't know how to replace it in my code?
Here is my code
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.CharsetUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* Created by JoeyJAL on 2015/3/14.
*/
public class MultiPartRequest extends Request<String> {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private String FILE_PART_NAME = "imageFile";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultiPartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, File file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
entity.setCharset(CharsetUtils.get("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildMultipartEntity();
httpentity = entity.build();
}
private void buildMultipartEntity() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart, ContentType.create("image/jpeg"), mFilePart.getName()));
if (mStringPart != null) {
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
#Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
httpentity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
System.out.println("Network Response "+ new String(response.data, "UTF-8"));
return Response.success(new String(response.data, "UTF-8"),
getCacheEntry());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return Response.success(new String(response.data), getCacheEntry());
}
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
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);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
This getQuery(List) will help to generate your output stream. You are uploading images so you can change that directly as output stream by replacing with getQuery() function.
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}

parsing json data in API url using jsonparser

I have a JSON data in this URL : http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f
when I try parsing using this jsonparser code :
package percobaan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String makeHttpRequest(String url, String method) {
return this.makeHttpRequest(url, method, null);
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
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();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
is.close();
json = sBuilder.toString();
} catch (Exception exception) {
exception.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
}
// return JSON String
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public String makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
// check for request method
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
// DefaultHttpClient httpClient = new
// DefaultHttpClient(httpParameters);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
// return JSON String
return json;
}
}
why the output just says :
{"data":[]}
this is my code :
package percobaan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* #author nafian
*/
public class Coba {
public static void main(String[] args) {
ArrayList<HashMap<String, String>> daftar_d = new ArrayList<HashMap<String, String>>();
JSONParser jsonParser = new JSONParser();
String link_url = "http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f";
List<NameValuePair> params = new ArrayList<NameValuePair>();
String parsing = jsonParser.makeHttpRequest(link_url, "POST",
params);
System.out.print(parsing);
// try {
// JSONObject json = new JSONObject(parsing).getJSONObject("data").getJSONObject("results");
// JSONArray caleg = json.getJSONArray("caleg");
//
// for (int i = 0; i < caleg.length(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
// JSONObject ar = caleg.getJSONObject(i);
// String nama = ar.getString("nama");
// String calon = ar.getString("role");
//
// JSONArray riwayat = ar.getJSONArray("riwayat_pendidikan");
// for (int j = 0; j < riwayat.length(); j++) {
// JSONObject ringkasan = riwayat.getJSONObject(j);
// String ringkasan_p = ringkasan.getString("ringkasan");
// map.put("pendidikan_r", ringkasan_p);
// }
//
// map.put("nama", nama);
// map.put("calon", calon);
// daftar_d.add(map);
//
// }
// } catch (JSONException ex) {
// ex.printStackTrace();
// }
// for (int i = 0; i < daftar_d.size(); i++) {
//
// System.out.println(daftar_d.get(i).get("pendidikan_r").toString());
// }
}
}
Am I missing something?
I suggest you use JSON-SIMPLE, it will literally simplify your life.
https://code.google.com/p/json-simple/
Here is a small example for the given URL.
Please note that's I'm using Jersey for establishing the connection, but you can pretty much use anything you like instead.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
...
String callString = "http://api.pemiluapi.org/calonpresiden/api/caleg/jk?apiKey=56513c05217f73e6be82d5542368ae4f";
Client client = Client.create();
WebResource webResource = client.resource(callString);
ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class);
if (clientResponse.getStatus() != 200) {
throw new RuntimeException("Failed"+ clientResponse.toString());
}
JSONObject resObj = (JSONObject)new JSONParser().parse(clientResponse.getEntity(String.class));
JSONObject data_obj = (JSONObject) resObj.get("data");
JSONObject results_obj = (JSONObject) data_obj.get("results");
JSONArray caleg_array = (JSONArray) results_obj.get("caleg");

Categories