How to call the github API form HttpsURLConnection in java - java

I need to change my branch named testingProtectedBranch1 as a protected branch with providing the following parameters
on
required_status_check : include_admins= true, strict= true, context= continuous-integration/travis-ci
restrictions: null
required_pull_request_reviews: include_admins=false
here is my code and the access token ( the variable token ) is provided by the user at the runtime.
public void setMasterBranchAsProtected() throws Exception{
String URLForCallingTheBranchAPI="https://api.github.com/repos/kasunsiyambalapitiya/testingProtectedBranch1/branches/master/protection";
String jsonInput="{\"required_status_checks\":{\"include_admins\":true,\"strict\":true,\"contexts\":[\"continuous-integration/travis-ci\"]},"
+ "\"restrictions\":null,"
+ "\"required_pull_request_reviews\":{\"include_admins\":false} ";
try {
URL urlObject= new URL(URLForCallingTheBranchAPI);
HttpsURLConnection httpsURLCon= (HttpsURLConnection)urlObject.openConnection();
httpsURLCon.setDoOutput(true);
httpsURLCon.setRequestMethod("PUT");
httpsURLCon.setRequestProperty("User-Agent", "Mozilla/5.0");
httpsURLCon.setRequestProperty("Accept","application/vnd.github.loki-preview+json");
httpsURLCon.setRequestProperty("Authorization", "Bearer "+token);
OutputStreamWriter outputStream= new OutputStreamWriter(httpsURLCon.getOutputStream());
outputStream.write(jsonInput);
int responseCode= httpsURLCon.getResponseCode();
outputStream.flush();
outputStream.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
but for the response code I receive 422 which resembles unprocessable entity. What I am doing wrong in here, please help me to figure this out. Thanks in advance.

Related

DELETE Request in Android doesn't connect to server

So my question is how can I create a DELETE Request to an URL in Android Studio Java. I already have an Async Task which GET json from URL. So my question now is how can I create a DELETE request
EDIT:
So right now I got this code:
int pos = arrlist.get(info.position).getId();
URL_DELETE = "http://testserver/test/tesst.php?id=" + pos + "&username=" + username + "&password=" + password;
URL url = null;
try {
url = new URL(URL_DELETE);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
To understand the content of the given URL should be deleted. But if I run the code nothing happens.
You need to call connect() on the HttpURLConnection. Right now you're not actually making a connection to the server.
Based on your comments on the other answer, you're also trying to run this code on the main (UI) thread - you'll need to change your code to run on a background thread.
If you're using OkHttp:
Request request = new Request.Builder().delete().url(url).build();
Response rawResponse = null;
try {
rawResponse = new OkHttpClient().newCall(request).execute();
} catch (IOException e) {
System.err.println(e.getMessage());
}
String responseAsString = rawResponse.body().string();

How to use HttpURLConnection PUT with query parameters?

How to make a PUT request using HttpURLConnection with query parameters?
I am trying to consume a third party REST API using HttpURLConnection but when I try to pass the parameters in the URL, it doesn't work and throw an error as shown below:
The REST API Url could not be found in the mappings registry
This is the code block that doesn't work for me as of now:
URL url;
StringBuffer response = new StringBuffer();
try
{
url = new URL(" http://thirdparty.com/party/api/v2/ksp/12/ks");
HttpURLConnection httpURL = (HttpURLConnection) url.openConnection();
httpURL.setDoOutput(true);
httpURL.setRequestMethod("PUT");
StringBuilder sbUrl = new StringBuilder("parameter1_id=");
sbUrl.append(getParameter1Value())
.append("&parameter2_id=")
.append(getParameter2Value());
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURL.getOutputStream()));
writer.write(sbUrl.toString());
writer.flush();
writer.close();
// throw the exception here in case invocation of web service
if (httpURL.getResponseCode() != 200)
{
// throw exception
}
else
{
//SUCCESS
}
}
catch (IOException e)
{
}
When I provide these parameters in the Body as form-data parameters, the REST API seems provide the response.
My question here is that how do I make this work with HttpURLConnection?
What have I tried till now?
I have tried to modify the above to something like below, but it doesn't work.
try
{
url = new URL(" http://thirdparty.com/party/api/v2/ksp/12/ks");
HttpURLConnection httpURL = (HttpURLConnection) url.openConnection();
httpURL.setDoOutput(true);
httpURL.setRequestMethod("PUT");
httpURL.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "----WebKitFormBoundarydklhfklsdfhlksh");
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"parameter1_id\"");
dataOutputStream.writeBytes("\r\n" + "parameter1Value" +"\r\n");
dataOutputStream.writeBytes("--" + "----WebKitFormBoundarydklhfklsdfhlksh");
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"parameter2_id\"");
dataOutputStream.writeBytes("\r\n" + "parameter2Value" + "\r\n");
dataOutputStream.writeBytes("--" + "----WebKitFormBoundarydklhfklsdfhlksh" + "--");
dataOutputStream.flush();
dataOutputStream.close();
urlConnection.connect();
// throw the exception here in case invocation of web service
if (httpURL.getResponseCode() != 200)
{
// throw exception
}
else
{
//SUCCESS
}
}
catch (IOException e)
{
}
EDIT: It throws an error with response code as 500
EDIT: Just to clarify, I'm not trying to upload a file but trying to send the parameters inside the BODY (like Query parameters instead of being sent as URL parameters).
Any pointers or suggestions on this are very much appreciated.
You talk about 'query parameters' and 'parameters in the URL', but neither of the approaches you show does any such things. Both your approaches (try to) send parameters in the request body, aka 'entity', not in the URL. Although body contents may be involved in an application-level query, they are NOT query string aka query parameters at the HTTP level. You also ask 'how do I make this work with HttpURLConnection' as if that were a change or difference when both your attempts already use it.
Your first attempt looks almost correct. It should work if
you .setRequestProperty("Content-type", "application/x-www-form-urlencoded") (which is not automatic) and your values either are URLencoded or don't need it (no reserved characters) (depending on the server it may be enough to have no ampersand or equalsign)
Your second attempt also is fairly close. You need to write a boundary before the first part as well, and for each part after Content-disposition: form-data; name="blah" you need one CRLF to end that header line and a second CRLF to end the header block. (MIME multipart format allows multiple header lines in general, although in this case only one is needed.) And the end boundary should be followed by a CRLF (after the extra --).
Both only if you have the URL correct, of course. Nothing will work without the correct URL.
Best Method to Call WebService with HttpUrlConnection PUT Method
ApiListener apilistener=null;
public void updateWorker()
{
progressDialog = ProgressDialog.show(myContext, "Message",
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
Thread runThread = new Thread(new Runnable() {
#Override
public void run() {
HttpAppRequest http = new HttpAppRequest();
try {
JSONObject paramObject = new JSONObject();
JSONObject dataObject = new JSONObject();
dataObject.put("id", csId);
}
paramObject.put("data", dataObject);
Log.e(AppConstants.TAG, "Param = " + paramObject.toString());
AppResponse response = http.putJSONData(BASE_URL + "/updateapi", paramObject.toString(), true);
if (response.getStatusCode() == 200) {
String csUpdateResult = response.getContentData();
Log.e(AppConstants.TAG, csUpdateResult);
JSONObject updateObject = new JSONObject(csUpdateResult);
Message completeMessage = handler.obtainMessage(1, updateObject);
completeMessage.sendToTarget();
} else {
handler.sendEmptyMessage(-1);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
String csMessage = myContext.getResources().getString(R.string.id_network_response_failure);
Message completeMessage = handler.obtainMessage(0, csMessage);
completeMessage.sendToTarget();
}
}
});
runThread.start();
}
/*******************************************************************************************************/ Handler Api Response Here
Handler handler= new Handler() {
#Override
public void handleMessage(Message inputMessage) {
progressDialog.dismiss();
if (inputMessage.what == 1) {
try {
JSONObject msgObject = (JSONObject) inputMessage.obj;
if (msgObject.has("result")) {
JSONObject resultObject = msgObject.getJSONObject("result");
if (resultObject.has("status")) {
String csStatus = resultObject.getString("status");
if (csStatus.equalsIgnoreCase("success")) {
apilistener.onUpdate(resultObject.getString("msg"));
}
} else {
if(resultObject.has("status"))
{
apilistener.onFailed(resultObject.getString("reason"));
}
}
}
} catch (JSONException e) {
CommonMethods.showMessageBox("", e.getMessage(), myContext);
}
} else if (inputMessage.what == 0) {
String csMessage = (String) inputMessage.obj;
CommonMethods.showMessageBox("", csMessage, myContext);
}
}
};
//CallBack Listener to parent Activity/Fragment
//User listener like this
public interface ApiListener extends EventListener
{
void onSuccess(String msg);
void onFaiulure(String msg);
}
public void setListener(ApiListener listener)
{
apilistener=listener;
}
}

Facebook Graph API request returning IOException "Hostname <fbcdn-profile-a.akamaihd.net> was not verified"

So I'm trying to simply fetch the user's profile photo from facebook but I'm getting a null response from facebook.request(path) and the IOException "Hostname fbcdn-profile-a.akamaihd.net was not verified".
Anyone know what could be causing this exception? Here's my method to call the facebook.request:
public Bitmap getUserPic(String path){
URL picURL = null;
try {
responsePic = facebook.request(path);
picURL = new URL(responsePic);
HttpURLConnection conn = (HttpURLConnection)picURL.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
userPic = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return userPic;
}
The string "path" is "me/picture"
Edit:
Also tried setting picURL to "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/260885_608260639_822979518_q.jpg" which is the url that the request should return. Still no photo :(
Thanks for any help
It sounds like a issue with the HTTPS connection used to get the image from the Facebook CDN. What happens if you request the regular HTTP version of the image?
E.g. http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/260885_608260639_822979518_q.jpg

Retrieving YouTube Channel insights though API

i'm using code below to get link for my channels insight data.
somehow my code is returning null as Link.
/* code***/
public static final String FEED_URL = "http://gdata.youtube.com/feeds/api/users/mychannelname/uploads"; //i put my channel's name in 'mychannelname'
String username = "mygmailid"; //here i entered my gmail id eg. mikeme#gmail.com
String password = "mypassword";
String developerKey = "AI39si7ffVeKWbG1k37***********************************************" //developer key
YouTubeService service = new YouTubeService( username ,developerKey); //just put username instead of clientid since client id no longer available
try {
service.setUserCredentials(username, password);
} catch (AuthenticationException e) {
System.out.println("Invalid login credentials.");
System.exit(1);
}
Query query = null;
try {
query = new Query(new URL( FEED_URL));
} catch (MalformedURLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
ChannelFeed channelFeed = null;
try {
channelFeed = service.query(query, ChannelFeed.class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(channelFeed.getEntries() + ":");
System.out.println(" Link : "+channelFeed.getLink("http://gdata.youtube.com/schemas/2007#insight.views", "text/html") + ":");
/********END**********/
i'm getting null as Link here
can anyone help me here to find what went wrong here?
Thanks,
Mike
It is most likely returning null because it can't find a link corresponding to the relative name you provided. Since the channel Insight information is only available for the channel corresponding to the user you're authenticated with it could be that it is not authorizing your user to view that channels insight data, which could be because your google account is not linked with your youtube account.
I would try printing out the response you're getting back to make sure you're getting all the data you think you're getting.

401 response when reading tweets

I'm new to mobile apps development. I'm developing a blackberry application which reads tweets from the user's timeline. So far I managed to get the OAuth access token. The problem happens when I try to use this access token to read the tweets I get a 401 response with a message "Unauthorized". I'm not using any libraries I'm doing everything on my own. Could anyone help me with this?
Thanks,
Here's the code:
HttpConnectionFactory factory = new HttpConnectionFactory( url,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Length", Integer.toString(header.getBytes().length));
os = httpConn.openOutputStream();
os.write(header.getBytes());
os.close();
os = null;
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
// Dialog.alert(httpConn.getDate()+" : "+System.currentTimeMillis());
if (resp == HttpConnection.HTTP_OK) {
XMLReader parser;
try {
parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
parser.parse(new InputSource(input));
for(int i=0 ; i<2 ; i++)
{
tweets.addElement( parser.getProperty("text").toString());
Dialog.alert(parser.getProperty("text").toString());
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dialog.alert("your tweet was posted successfully :)");
}
Dialog.alert(httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
return (httpConn.getResponseCode()+": "+httpConn.getResponseMessage());
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I'm not an expert in OAuth, however just a note:
This:
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
and this:
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
are mutually exclusive things. You are posting data to server, so it should be a POST (not GET).

Categories