Skip to content

Commit

Permalink
Change to OkHttp
Browse files Browse the repository at this point in the history
  • Loading branch information
ABPSoft committed Apr 4, 2019
1 parent fe3b98a commit 0e6f86c
Show file tree
Hide file tree
Showing 7 changed files with 113 additions and 115 deletions.
7 changes: 6 additions & 1 deletion ABPWebService/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,14 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

//این باید حتماً توی پروژه باشه. چون نباشه کار نمیکنه
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.squareup.okhttp3:okhttp:3.14.0"
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@
import java.net.MalformedURLException;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.BufferedSink;

/**
* Created by ABP on 8/28/2016.
*/
Expand Down Expand Up @@ -71,129 +82,104 @@ public void run()
{
String requestData;

if(inputName==null)
RequestBody requestBody;

if(fileInputName!=null)
{
String mimeType=getMimeType(file.getAbsolutePath());

requestBody=new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(inputName,data)
.addFormDataPart(fileInputName,file.getName(),RequestBody.create(MediaType.parse(mimeType),file))
.build();
}
else if(inputName!=null)
{
requestData=data;
requestBody=new FormBody.Builder()
.add(inputName,data)
.build();
}
else
{
requestData=inputName+"="+data;
requestBody=new RequestBody()
{
@Override
public MediaType contentType()
{
return MediaType.parse("application/json; charset=utf-8");
}

@Override
public void writeTo(BufferedSink sink) throws IOException
{
sink.writeUtf8(data);
}
};
}


URL apiUrl=null;
OkHttpClient client=new OkHttpClient();

Request request=new Request.Builder()
.url(url)
.post(requestBody)
.build();

try
{
apiUrl=new URL(url);

HttpURLConnection httpURLConnection=(HttpURLConnection) apiUrl.openConnection();

httpURLConnection.setConnectTimeout(connectTimeout);
httpURLConnection.setReadTimeout(readTimeout);

if(inputName==null)
{
httpURLConnection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
}

httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);

DataOutputStream dataOutputStream=null;

if(file!=null)
client.newCall(request).enqueue(new Callback()
{
String boundary="***************";

String lineEnd="\r\n";
String twoHyphens="--";

FileInputStream fileInputStream=new FileInputStream(file);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestProperty("ENCTYPE","multipart/form-data");
httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);


String content="Content-Disposition: form-data; name=\""+inputName+"\""+lineEnd+lineEnd+data+lineEnd+lineEnd;
content+=twoHyphens+boundary+lineEnd+"Content-Disposition: form-data; name=\""+fileInputName+"\";filename=\""+file.getName()+"\""+lineEnd+"Content-Type:"+ getMimeType(file.getAbsolutePath())+lineEnd;

dataOutputStream=new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes(twoHyphens+boundary+lineEnd);
dataOutputStream.writeBytes(content);
dataOutputStream.writeBytes(lineEnd);

int byteAvailable, bufferSize, bytesRead;
byte[] buffer;
int maxBufferSize=1024*1024;

byteAvailable=fileInputStream.available();
bufferSize=Math.min(byteAvailable,maxBufferSize);

buffer=new byte[bufferSize];
bytesRead=fileInputStream.read(buffer,0,bufferSize);

while(bytesRead>0)
@Override
public void onFailure(Call call,final IOException e)
{
dataOutputStream.write(buffer,0,bufferSize);
byteAvailable=fileInputStream.available();
bufferSize=Math.min(byteAvailable,maxBufferSize);

bytesRead=fileInputStream.read(buffer,0,bufferSize);
if(iOnNetwork!=null)
{
HANDLER.post(new Runnable()
{
@Override
public void run()
{
iOnNetwork.onError(-6,"عدم توانایی در اتصال به سرور!",e);
}
});
}
}

dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens+boundary+twoHyphens+lineEnd);
}
else
{
OutputStreamWriter osw=new OutputStreamWriter(httpURLConnection.getOutputStream(),"UTF-8");
osw.write(requestData);
osw.flush();
}

if(dataOutputStream!=null)
{
dataOutputStream.close();
dataOutputStream.flush();
}

BufferedReader br=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

StringBuilder strAll=new StringBuilder();
String strLine;
while((strLine=br.readLine())!=null)
{
strAll.append(strLine).append("\n");
}

strAll=new StringBuilder(strAll.toString().trim());

Log.i("WebService","Response: "+strAll);

if(iOnNetwork!=null)
{
iOnNetwork.onResponse(strAll.toString());
}
}
catch(MalformedURLException e)
{
e.printStackTrace();

if(iOnNetwork!=null)
{
HANDLER.post(new Runnable()
@Override
public void onResponse(Call call,final Response response) throws IOException
{
@Override
public void run()
if(response.isSuccessful())
{
iOnNetwork.onError(-5,"Error in Assign URL");
String body=response.body().string();

Log.i("WebService","Response: "+body);

if(iOnNetwork!=null)
{
iOnNetwork.onResponse(body);
}
}
});
}
else
{
if(iOnNetwork!=null)
{
HANDLER.post(new Runnable()
{
@Override
public void run()
{
iOnNetwork.onError(-6,"عدم توانایی در اتصال به سرور!",new Exception(response+""));
}
});
}
}
}
});


}
catch(IOException e)
catch(final Exception e)
{
e.printStackTrace();

Expand All @@ -204,7 +190,7 @@ public void run()
@Override
public void run()
{
iOnNetwork.onError(-6,"عدم توانایی در اتصال به سرور!");
iOnNetwork.onError(-6,"عدم توانایی در اتصال به سرور!",e);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ public interface IOnNetwork
{
public void onResponse(String response);

public void onError(int errorCode,String errorText);
public void onError(int errorCode,String errorText,Exception exception);
}
10 changes: 8 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,21 @@ android {
applicationId "com.aminbahrami.abpwebservicelib"
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
versionCode 11
versionName "1.1"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

//این باید حتماً باشه. چون نباشه کار نمیکنه
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
}

dependencies {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public void onClick(View view)
private void sendRequest()
{
ABPWebService abpWebService=new ABPWebService();
abpWebService.setUrl("http://192.168.1.2/test/androidUploadFile/upload.php");
abpWebService.setUrl("http://192.168.1.7/test/androidUploadFile/upload.php");

//Check Permission in the feature
File file=new File(Environment.getExternalStorageDirectory()+"/test.jpg");
Expand All @@ -64,12 +64,12 @@ public void onResponse(String response)
}

@Override
public void onError(int errorCode,String errorText)
public void onError(int errorCode,String errorText,Exception e)
{

}
});

abpWebService.sendRequest("data",object.toString(),"file",file);
abpWebService.sendRequest(null,object.toString());
}
}
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'

// NOTE: Do not place your application dependencies here; they belong
Expand Down
3 changes: 2 additions & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#Thu Apr 04 19:13:53 IRDT 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip

0 comments on commit 0e6f86c

Please sign in to comment.